<script setup lang="tsx">
import { computed, PropType, reactive, ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ElButton } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { addTaskNeedApi, deleteTaskNeedApi, putTaskNeedApi } from '@/api/dispatch/taskpool'
import { useUserStoreWithOut } from '@/store/modules/user'
import { useEventBus } from '@/hooks/event/useEventBus'

const userStore = useUserStoreWithOut()
const userInfo = computed(() => userStore.getUserInfo)

const { t } = useI18n()

const { emit } = useEventBus()

const props = defineProps({
  showAction: {
    type: Boolean as PropType<boolean>,
    default: true
  },
  ticketId: {
    type: String as PropType<string>,
    default: undefined
  },
  data: {
    type: Array as PropType<any[]>,
    default: () => []
  }
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('common.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'name',
    label: '辅料名称',
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'type',
    label: '辅料类型',
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'number',
    label: '数量',
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'unit',
    label: '单位',
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'remark',
    label: '备注',
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'action',
    label: t('common.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElButton link type="primary" size="small" onClick={() => action(data.row, 'edit')}>
                编辑
              </ElButton>
              <ElButton link type="primary" size="small" onClick={() => delData(data.row)}>
                删除
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const AddAction = () => {
  dialogTitle.value = t('common.add')
  actionType.value = 'add'
  currentRow.value = undefined
  dialogVisible.value = true
}

const delLoading = ref(false)

const delData = async (row) => {
  delLoading.value = true
  try {
    const res = await deleteTaskNeedApi([row.id])
    if (res) emit('updateTask', props.ticketId)
  } finally {
    delLoading.value = false
  }
}

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.edit' : 'common.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res =
        actionType.value === 'add'
          ? await addTaskNeedApi({ ticket_id: props.ticketId, ...formData })
          : await putTaskNeedApi({ ticket_id: props.ticketId, ...formData })
      if (res) emit('updateTask', props.ticketId)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}
</script>

<template>
  <div class="p-10px">
    <div class="mb-10px" v-if="showAction">
      <ElButton type="primary" @click="AddAction">添加辅料</ElButton>
    </div>
    <Table :columns="allSchemas.tableColumns" node-key="id" :data="data" />
  </div>

  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    max-height="250px"
    append-to-body
  >
    <Write ref="writeRef" :current-row="currentRow" :form-schema="allSchemas.formSchema" />
    <template #footer>
      <ElButton type="primary" :loading="saveLoading" @click="save">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>
